import { Card, Breadcrumb, Form, Radio, Select, DatePicker, Button, Table, Tag, Space, Popconfirm  } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { Link } from 'react-router-dom'
import locale from 'antd/es/date-picker/locale/zh_CN'
import img404 from '@/assets/error.png'
import { useEffect, useState } from 'react'
import { http, history } from '@/utils'
import { useStore } from '@/store'

const { Option } = Select
const { RangePicker } = DatePicker

const Article = () => {
  // 文章列表数据管理
  const [articleData, setArticleData] = useState({
    list: [],
    count: 0
  })
  // 参数管理
  const [params, setParams] = useState({
    page: 1,
    per_page: 5
  })
  useEffect(() => {
    async function getArticleList() {
      const res = await http.get('/mp/articles', { params })
      const { results, total_count } = res.data
      setArticleData({
        list: results,
        count: total_count
      })
    }
    getArticleList()
  }, [params])
  
  // 删除文章
  const deleteArticle = async (data) => {
   await http.delete(`/mp/articles/${data.id}`)
  // 更新列表
    setParams({
      page: 1,
      per_page: 5
    })
  }

  // 表格列数据
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      width: 120,
      render: cover => {
        return <img src={ cover.images[0] || img404} width={80} height={60} alt="" />
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 220
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: data => <Tag color='green'> 审核通过 </Tag>
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate'
    },
    {
      title: '阅读数',
      dataIndex: 'read_count'
    },
    {
      title: '评论数',
      dataIndex: 'comment_count'
    },
    {
      title: '点赞数',
      dataIndex: 'like_count'
    },
    {
      title: '操作',
      render: data => {
        return (
          <Space size="middle">
            <Button
              type='primary'
              shape='circle'
              icon={<EditOutlined />}
              onClick={() => history.push(`/publish?id=${data.id}`)}
            />
            <Popconfirm
              onConfirm={() => { deleteArticle(data) }}
              title='确认删除？'
              okText='确认'
              cancelText='取消'
            >
              <Button
                type='primary'
                danger
                shape='circle'
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Space>
        )
      }
    }
  ]
  const onSearch = (e) => {
    const {status, channel_id, date} = e
    const newParams = {}
    newParams.status = status
    if (channel_id) {
    newParams.channel_id = channel_id
    }
    if (date) {
    newParams.begin_pubdate = date[0].format('YYYY-MM-DD')
    newParams.end_pubdate = date[1].format('YYYY-MM-DD')
    }
    setParams({
      ...params,
      ...newParams
    })
  }
  const pageChange = (page) => {
    setParams({
      page,
      per_page: 5
    })
  }
  const { channelStore } = useStore()
  return (
    <div>
      {/* 筛选条件 */}
      <Card
        title={
          <Breadcrumb separator='>'>
            <Breadcrumb.Item>
              <Link to='/'> 首页 </Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              内容管理
            </Breadcrumb.Item>
          </Breadcrumb>
        }
        style={{ marginBottom: 20 }}
      > 
        <Form initialValues={{ status: undefined}} onFinish={onSearch}>
          <Form.Item label='状态' name='status'>
            <Radio.Group>
              <Radio value={undefined}>全部</Radio>
              <Radio value={1}>草稿</Radio>
              <Radio value={2}>待审核</Radio>
              <Radio value={3}>审核通过</Radio>
              <Radio value={4}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label='频道' name='channel_id'>
            <Select
              placeholder="请选择频道"
              style={{width: 120}}
            >
              {channelStore.channelList.map(item => (
                <Option key={item.id} value={item.id}> {item.name} </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item label='日期' name='date'>
            <RangePicker locale={locale}></RangePicker>
          </Form.Item>

          <Form.Item>
            <Button type='primary' htmlType='submit' style={{marginLeft: 80}}> 筛选 </Button>
          </Form.Item>
        </Form>
      </Card>

      {/* 表格*/}
      <Card title={`根据筛选条件一共获取到${articleData.count}条结果`}>
        <Table
          rowKey='id'
          columns={columns}
          dataSource={articleData.list}
          pagination={{
            current: params.page,
            pageSize: params.per_page,
            total:articleData.count,
            // position: ['bottomCenter'],
            onChange: pageChange
          }}
        ></Table>
      </Card>
    </div>
  )
}

export default Article